var prefix = ctx +"module/terminal/record"
$(function() {
    load();
});
function load(){
    layui.use(['form','laydate','table'], function() {
        var form = layui.form ,laydate = layui.laydate,
            table = layui.table;//载入table模块
        laydate.render({
            elem: '#begin_date',
            isInitValue: false,
        });
        laydate.render({
            elem: '#end_date',
            isInitValue: false,
        });
        var searchParams = {};
        searchParams['search_eq_terminalId']=$('#terminalId').val();
        searchParams['search_eq_isClean']=$('#isClean').val();
        searchParams['search_eq_checkState']=$('#checkState').val();
        searchParams['search_eq_shopId']=$('#shopId').val();

        if($('#begin_date').val()!="" && $('#end_date').val()!=""){
            searchParams['search_ge_createTime']=$('#begin_date').val() + " 00:00:00";
            searchParams['search_le_createTime']=$('#end_date').val()+ " 23:59:59";
        }
        var isClean =  $('#isClean').val();
        var title = "";
        if(isClean == 0){
            title = "巡检";
        } else if(isClean == 1){
            title = "清理";
        }else if(isClean == 2){
            title = "保养";
        }

        //初始化table
        table.render({
            elem: '#exampleTable',//承载数据的table Id
            url: prefix + "/list",//请求数据连接
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter'],
            cellMinWidth: 80,//全局定义所有常规单元格的最小宽度（默认：60）
            even: true,//是否开启隔行变色
            loading:true,//是否显示加载条
            where :{
                searchParams:searchParams,
                sorts:{"id":"desc"}
            },
            //page: true,//是否分页
            page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                layout: [ 'prev', 'page', 'next', 'skip', 'count','limit'] //自定义分页布局
            },
            defaultToolbar: false,
            cols: [[
                { type : 'checkbox',fixed : 'left' },
                // { type : 'numbers',title: '序号', width:'5%'},
                { field : 'shopName',  title : '企业名称',  align : 'center', },
                { field : 'terminalName',  title : '设备名称', align : 'center',   },
                { field : 'terminalNum',  title : '设备编号', align : 'center',   },
                { field : 'userName',  title : title + '人', align : 'center',   },
                { field : 'createTime',  title : title + '时间', align : 'center',   },
                { field : 'checkResult',  title : title + '说明', align : 'center',   },
                { title : '相关图片', align : 'center',
                    templet: function (item) {
                        // console.log('相关图片 item',item.imgsList)
                        var imgs = "";
                        if(item.imgsList!=undefined){
                            if(item.imgsList.length > 0){
                                for(var index in item.imgsList){
                                    imgs += "<img src='"+item.imgsList[index]+"' style='margin-left: 5px;' width='50' height='50' />";
                                }
                            }
                        }
                        return imgs;
                    },
                },
                { title : '状态', align : 'center',
                    templet: function (item) {
                        var css = loadDictCssStyle('check-state')[item.checkState]
                        return '<span class="'+css+'">' + (loadCategory('check-state')[item.checkState] ? loadCategory('check-state')[item.checkState] : '') + '</span>';
                    },
                },
                { title: '操作', templet: '#currentTableBar', align: "center"}
            ]],
            id: 'currentTableId',//表格Id
            done: function(res, curr, count){
                // $('.layui-table-fixed-r').removeClass('layui-hide');
                $(".layui-table img").each(function() {
                    $(this).click(function() {
                        previewImg(this);
                    })
                });
            } //解决最右侧列不能固定的问题
        });
        /**
         * 操作栏tool  监听事件
         */
        table.on('tool(currentTableFilter)', function (obj) {
            if (obj.event === 'edit') {  // 监听添加操作
                console.log('obj',obj.data.id)
                edit(obj.data.id);
            } else if (obj.event === 'delete') {  // 监听删除操作
                console.log('obj',obj.data.id)
                remove(obj.data.id);
            }else if (obj.event === 'record') {  // 监听删除操作
                goRecordList(obj.data.id);
            }
        });
        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            //执行搜索重载
            reLoad();
            return false;
        });

        /**
         * 操作栏tool  监听事件
         */
        table.on('toolbar(currentTableFilter)', function (obj) {
            if (obj.event === 'back') {  // 监听添加操作
                goBack();
            }else if(obj.event === 'export'){
                exportExcel()
            }else if(obj.event === 'batchRemove'){
                var checkStatus = table.checkStatus('currentTableId'),data = checkStatus.data;
                checkedArr = data;
                var ids = [];
                for(var index in checkedArr){
                    ids.push(checkedArr[index].id);
                }
                if (ids.length < 1) {
                    layer.msg('无选中项');
                    return false;
                }
                batchRemove(ids);
            }
        });
    });
}
function exportExcel(){
    var begin_date = $("#begin_date").val();
    var end_date = $("#end_date").val();
    var isClean = $("#isClean").val();
    var shopId = $("#shopId").val();
    var checkState = $("#checkState").val();
    window.location.href = ctx + 'module/terminal/record/exportExcel?begin_date='
        +begin_date+'&end_date='+end_date+"&is_clean="+isClean+'&shopId='+shopId+'&checkState='+checkState;
}


function goBack(){
    var id = $("#shopId").val();
    window.location.href = ctx + 'module/terminal/'+id;
}


function previewImg(obj) {
    var img = new Image();
    img.src = obj.src;
    var imgHtml = "<img src='" + obj.src + "' width='600' height='500'/>";
    //弹出层
    layer.open({
        type: 1,
        // shade: true,
        shadeClose : true, // 点击遮罩关闭层
        title: false, //不显示标题
        area:[ '600px', '500px' ],
        content: imgHtml, //捕获的元素，注意：最好该指定的元素要存放在body最外层，否则可能被其它的相对元素所影响
        cancel: function () {

        }
    });
}

function reLoad() {
    var searchParams = {};
    searchParams['search_eq_terminalId']=$('#terminalId').val();
    searchParams['search_eq_isClean']=$('#isClean').val();
    searchParams['search_eq_checkState']=$('#checkState').val();
    searchParams['search_eq_shopId']=$('#shopId').val();

    if($('#begin_date').val()!="" && $('#end_date').val()!=""){
        searchParams['search_ge_createTime']=$('#begin_date').val() + " 00:00:00";
        searchParams['search_le_createTime']=$('#end_date').val()+ " 23:59:59";
    }
    layui.use(['table'], function() {
        var table = layui.table;//载入table模块
        table.reload('currentTableId', {
            page: {curr: 1}
            , where: {
                searchParams: searchParams,
                sorts:{"id":"desc"}
            }
        }, 'data');
    });
}

function add() {
    var index = layer.open({
        type : 2,
        title : '增加',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '800px', '420px' ],
        content : prefix + '/add' // iframe的url
    });
    layer.full(index);
}

function batchAdd() {
    var index = layer.open({
        type : 2,
        title : '批量增加',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '800px', '320px' ],
        content : ctx + 'module/terminal/goBatchAdd' // iframe的url
    });
}

function goRecordList(id) {
    window.location.href = ctx + 'module/terminal/record/'+id;
}

function edit(id) {
    var index = layer.open({
        type : 2,
        title : '编辑',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '800px', '520px' ],
        content : prefix + '/edit/' + id // iframe的url
    });

    layer.full(index);
}
function remove(id) {
    layer.confirm('确定要删除选中的记录？', {
        btn : [ '确定', '取消' ]
    }, function() {
        $.ajax({
            url : prefix+"/remove",
            type : "post",
            data : {
                'id' : id
            },
            success : function(r) {
                if (r.code==0) {
                    layer.msg(r.msg);
                    reLoad();
                }else{
                    layer.msg(r.msg);
                }
            }
        });
    })
}

function batchRemove(ids) {
    layer.confirm("确认要删除选中的'" + ids.length + "'条数据吗?", {
        btn : [ '确定', '取消' ]
        // 按钮
    }, function() {
        $.ajax({
            type : 'POST',
            data : {
                "ids" : ids
            },
            url : prefix + '/batchRemove',
            success : function(r) {
                if (r.code == 0) {
                    layer.msg(r.msg);
                    reLoad();
                } else {
                    layer.msg(r.msg);
                }
            }
        });
    }, function() {});
}
